/**
 * storeQuery.jsp引用
 * @param $
 * @param win
 * @param doc
 */
var url = '/business/storeQueryServlet';
var sumType = 10;
(function($, win, doc){
	// 查询条件
	var createCondCombox = function(){
		var param = Param.getReadCmd();
		var cond = {};
		param = Param.buildParam(param,cond);
		param[Param.CMDTYPEKEY] = 0;
		param[Param.CMDVALUEKEY] = 1;
		
		// 区域
//		$('#area').combobox({
//		    url: CONTEXT_PATH + Global.commonUrl,
//			queryParams : param,
//			method : 'post',
//		    valueField: 'value',
//		    textField: 'text',
//		    loader: Util.combox.loader,
//		    onSelect: function(){ 
//		    	var cond = getCond2();
//				param[Param.CMDTYPEKEY] = 1;
//				param[Param.CMDVALUEKEY] = 1;
//				param = Param.buildParam(param,cond);
//				$('#shop').combobox({
//					url: CONTEXT_PATH + Global.commonUrl,
//					queryParams : param,
//					method : 'post',
//				    valueField: 'value',
//				    textField: 'text',
//				    loader: Util.combox.loader
//				}).combobox('setValue', '-');
//		     }
//		}).combobox('setValue', '-');
		// 分店
//		param = Param.getReadCmd();
//		param[Param.CMDTYPEKEY] = 1;
//		param[Param.CMDVALUEKEY] = 1;
//		var cond = {};
//		param = Param.buildParam(param,cond);
//		$('#shop').combobox({
//			url: CONTEXT_PATH + Global.commonUrl,
//			queryParams : param,
//			method : 'post',
//		    valueField: 'value',
//		    textField: 'text',
//		    loader: Util.combox.loader
//		}).combobox('setValue', '-');
		//=================================
		param = Param.getReadCmd();
		param[Param.CMDTYPEKEY] = 1;
		param[Param.CMDVALUEKEY] = 1;
		var cond = {};
		param = Param.buildParam(param,cond);
		var param = {
			shopType:"'加盟','直营'",
			zoneCode:''
		}
		$('#shop').combobox({
			prompt:'请输入或选择分店', 
	        url: CONTEXT_PATH + '/ktcount/getShop',
	        queryParams:param,
			method : 'post',
		    valueField: 'SHOP_ID',
		    textField: 'SHOP_NAME',
		    groupField:'SHOP_TYPE',
            multiple:true,
		    loader: Util.combox.loader,
		    groupFormatter: function(group){
				return '<span style="color:red">' + group + '</span>';
			},
		    onClick: function(node) { 
                attributeShow($("#shop").combotree("getValue")); 
            }, 
            filter: function(q, row){ 
                var opts = $(this).combobox('options'); 
                //return row[opts.textField].indexOf(q) == 0; 
                return row[opts.textField].indexOf(q)>-1;//将从头位置匹配改为任意匹配 
            }, 
		    formatter: function (row) {
                var opts = $('#shop').combobox('options');
                return '<input type="checkbox" class="combobox-checkbox">' + row[opts.textField]
            },
            onLoadSuccess: function (val) {  //下拉框数据加载成功调用
            	//如果只有一个店铺就默认选中这个店铺
	           	 var shopVal = JSON.stringify(val);
	           	 var obj = eval('(' + shopVal + ')');
	           	 console.log(obj);
	           	 var setText = obj[0].SHOP_NAME;
	           	 var setVal = obj[0].SHOP_ID;
	           	console.log(setVal);
	           	if(val.length == '1'){
	           		$('#shop').combobox('setText',setText);
	           		$('#shop').combobox('setValue',setVal);
	           		$('#shop').combobox('disable');
	           	}
           	
                var opts = $('#shop').combobox('options');
                var target = this;
                var values = $(target).combobox('getValues');//获取选中的值的values
                $.map(values, function (value) {
                    var el = opts.finder.getEl(target, value);
                    el.find('input.combobox-checkbox')._propAttr('checked', true); 
                })
            },
            onSelect: function (row) { //选中一个选项时调用
                var opts = $('#shop').combobox('options');
                //获取选中的值的values
                $("#shop").val($('#shop').combobox('getValues'));
			   //设置选中值所对应的复选框为选中状态
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', true);
            },
            onUnselect: function (row) {//不选中一个选项时调用
                var opts = $('#shop').combobox('options');
                //获取选中的值的values
                $("#shop").val($('#shop').combobox('getValues'));
              
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', false);
            },
		});
		//=================================
		// 商品类型
//		param = Param.getReadCmd();
//		param[Param.CMDTYPEKEY] = 2;
//		param[Param.CMDVALUEKEY] = 1;
//		var cond = {};
//		param = Param.buildParam(param,cond);
//		$('#goodsType').combobox({
//			url: CONTEXT_PATH + Global.commonUrl,
//			queryParams : param,
//			method : 'post',
//		    valueField: 'value',
//		    textField: 'text',
//		    loader: Util.combox.loader
//		}).combobox('setValue', '-');
		// 供应商
//		param = Param.getReadCmd();
//		param[Param.CMDTYPEKEY] = 3;
//		param[Param.CMDVALUEKEY] = 1;
//		var cond = {};
//		param = Param.buildParam(param,cond);
//		$('#supplier').combobox({
//			url: CONTEXT_PATH + Global.commonUrl,
//			queryParams : param,
//			method : 'post',
//		    valueField: 'value',
//		    textField: 'text',
//		    loader: Util.combox.loader
//		}).combobox('setValue', '-');
		// 供应商
		param = Param.getReadCmd();
		param[Param.CMDTYPEKEY] = 3;
		param[Param.CMDVALUEKEY] = 1;
		var cond = {};
		param = Param.buildParam(param,cond);
		$('#supplier').combobox({
			url: CONTEXT_PATH + '/ktcount/getSupplier',
			queryParams : param,
			method : 'post',
		    valueField: 'ID',
		    textField: 'NAME',
		    multiple:true,
		    loader: Util.combox.loader,
		    filter: function(q, row){ 
                var opts = $(this).combobox('options'); 
                //return row[opts.textField].indexOf(q) == 0; 
                return row[opts.textField].indexOf(q)>-1;//将从头位置匹配改为任意匹配 
            }, 
		    formatter: function (row) {
                var opts = $('#supplier').combobox('options');
                return '<input type="checkbox" class="combobox-checkbox">' + row[opts.textField]
            },
            onLoadSuccess: function () {  //下拉框数据加载成功调用
                var opts = $('#supplier').combobox('options');
                var target = this;
                var values = $(target).combobox('getValues');//获取选中的值的values
                $.map(values, function (value) {
                    var el = opts.finder.getEl(target, value);
                    el.find('input.combobox-checkbox')._propAttr('checked', true); 
                })
            },
            onSelect: function (row) { //选中一个选项时调用
                var opts = $('#supplier').combobox('options');
                //获取选中的值的values
                $("#supplier").val($('#supplier').combobox('getValues'));
			   //设置选中值所对应的复选框为选中状态
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', true);
            },
            onUnselect: function (row) {//不选中一个选项时调用
                var opts = $('#supplier').combobox('options');
                //获取选中的值的values
                $("#supplier").val($('#supplier').combobox('getValues'));
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', false);
            } 
		});
		// 品牌
//		param = Param.getReadCmd();
//		param[Param.CMDTYPEKEY] = 4;
//		param[Param.CMDVALUEKEY] = 1;
//		var cond = {};
//		param = Param.buildParam(param,cond);
//		$('#brand').combobox({
//			url: CONTEXT_PATH + Global.commonUrl,
//			queryParams : param,
//			method : 'post',
//		    valueField: 'value',
//		    textField: 'text',
//		    loader: Util.combox.loader
//		}).combobox('setValue', '-');
		// 品牌
		param = Param.getReadCmd();
		param[Param.CMDTYPEKEY] = 4;
		param[Param.CMDVALUEKEY] = 1;
		var cond = {};
		param = Param.buildParam(param,cond);
		$('#brand').combobox({
			url: CONTEXT_PATH + '/ktcount/getBrand',
			queryParams : param,
			method : 'post',
		    valueField: 'ID',
		    textField: 'NAME',
		    multiple:true,
		    loader: Util.combox.loader,
		    filter: function(q, row){ 
                var opts = $(this).combobox('options'); 
                //return row[opts.textField].indexOf(q) == 0; 
                return row[opts.textField].indexOf(q)>-1;//将从头位置匹配改为任意匹配 
            }, 
		    formatter: function (row) {
                var opts = $('#brand').combobox('options');
                return '<input type="checkbox" class="combobox-checkbox">' + row[opts.textField]
            },
            onLoadSuccess: function () {  //下拉框数据加载成功调用
                var opts = $('#brand').combobox('options');
                var target = this;
                var values = $(target).combobox('getValues');//获取选中的值的values
                $.map(values, function (value) {
                    var el = opts.finder.getEl(target, value);
                    el.find('input.combobox-checkbox')._propAttr('checked', true); 
                })
            },
            onSelect: function (row) { //选中一个选项时调用
                var opts = $('#brand').combobox('options');
                //获取选中的值的values
                $("#brand").val($('#brand').combobox('getValues'));
			   //设置选中值所对应的复选框为选中状态
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', true);
            },
            onUnselect: function (row) {//不选中一个选项时调用
                var opts = $('#brand').combobox('options');
                //获取选中的值的values
                $("#brand").val($('#brand').combobox('getValues'));
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', false);
            }
		});
	};
	/**
	 * 创建条件对象
	 */
	//	级联
	var getCond2 = function(){
		var cond = {};
		//区域
		var area = $('#area').combobox('getValue');
		cond['ZONE_CODE'] = Param.buildParamItem('=', area, Param.SQLType.VARCHAR); 
		return cond;
	}
	var getCond = function() {
		var cond = {};
		// 时间
//		var startTime = $('#startTime').datebox('getValue');
//		cond['startTime'] = Param.buildParamItem('=', startTime, Param.SQLType.VARCHAR); 
//		var endTime = $('#endTime').datebox('getValue');
//		cond['endTime'] = Param.buildParamItem('=', endTime, Param.SQLType.VARCHAR); 
		//区域
		//var area = $('#area').combobox('getValue');
		var area = $('#areaCode').val();
		
		if(area == ""){
			area = '-'

		}
		cond['area'] = Param.buildParamItem('=', area, Param.SQLType.VARCHAR); 
		//分店
		var shop = $('#shop').combobox('getValue');
		if(shop == undefined){
			shop = '-'
		}
		cond['shop'] = Param.buildParamItem('=', shop, Param.SQLType.VARCHAR); 
		//商品类型
		//var goodsType = $('#goodsType').combobox('getValue');
		var goodsType = $('#typeId').val();
		if(goodsType == ""){
			goodsType = '-'

		}
		cond['goodsType'] = Param.buildParamItem('=', goodsType, Param.SQLType.VARCHAR); 
		//品牌
		var brand = $('#brand').combobox('getValue');
		cond['brand'] = Param.buildParamItem('=', brand, Param.SQLType.VARCHAR); 
		//供应商
		var supplier = $('#supplier').combobox('getValue');
		cond['supplier'] = Param.buildParamItem('=', supplier, Param.SQLType.VARCHAR); 
		//库存大于
		var moreThan = $('#moreThan').val();
		if(moreThan==""){
			moreThan = "0";
		}
		cond['moreThan'] = Param.buildParamItem('=', moreThan, Param.SQLType.VARCHAR); 
		//库存小于
		var lessThan = $('#lessThan').val();
		if(lessThan==""){
			lessThan = "0";
		}
		cond['lessThan'] = Param.buildParamItem('=', lessThan, Param.SQLType.VARCHAR); 
		//助记码
		var helpCode = $('#helpCode').val();
		if(helpCode==""){
			helpCode = "-";
		}
		cond['helpCode'] = Param.buildParamItem('=', '%'+helpCode+'%', Param.SQLType.VARCHAR); 
		//第三方编码
		var thirdEncode = $('#thirdEncode').val();
		if(thirdEncode==""){
			thirdEncode = "-";
		}
		//cond['thirdEncode'] = Param.buildParamItem('=', '%'+thirdEncode+'%', Param.SQLType.VARCHAR); 
		//自编码
		var selfEncode = $('#selfEncode').val();
		if(selfEncode==""){
			selfEncode = "-";
		}
		cond['selfEncode'] = Param.buildParamItem('=', '%'+selfEncode+'%', Param.SQLType.VARCHAR); 
		//货号
		var artNo = $('#artNo').val();
		if(artNo==""){
			artNo = "-";
		}
		cond['artNo'] = Param.buildParamItem('=', '%'+artNo+'%', Param.SQLType.VARCHAR); 
		//商品名称
		var goodsName = $('#goodsName').val();
		if(goodsName==""){
			goodsName = "-";
		}
		cond['goodsName'] = Param.buildParamItem('=', '%'+goodsName+'%', Param.SQLType.VARCHAR); 
		//非零商品
		/*cond['validGoods'] = Param.buildParamItem('=', '-', Param.SQLType.VARCHAR); 
		//淘汰商品
		cond['fallGoods'] = Param.buildParamItem('=', '-', Param.SQLType.VARCHAR); 
		$('input:checkbox').each(function() {
			if ("checked"==$(this).attr('checked')) {
				var checkedValue = $(this).val();
				if(checkedValue==1){
					cond['validGoods'] = Param.buildParamItem('=', '1', Param.SQLType.VARCHAR); 
				}else if(checkedValue==2){
					cond['fallGoods'] = Param.buildParamItem('=', '1', Param.SQLType.VARCHAR); 
				}
			}
		});*/
		return cond;
	};
	//清空店铺输入框
	 var shopChange = function(){  
		 $('#shop').combobox('clear');
	 }
	//清空品牌输入框
	 var brandChange = function(){
		 $('#brand').combobox('clear');
	 }
	//清空供应商输入框
	 var supplierChange = function(){
		 $('#supplier').combobox('clear');
	 }
	 
	// 查询
	var onQuery = function(){
		//获取参数
//		var startTime = $('#startTime').datebox('getValue');
//		var endTime = $('#endTime').datebox('getValue');
		var area = $('#areaCode').val();
		var shopIds = $('#shop').combobox('getValues');
		if(shopIds[0] == '-'){
			shopIds.splice(0,1);
		}
		var shopIds = shopIds.toString();
		var goodsType = $('#typeId').val();
		var brandIds = $('#brand').combobox('getValues');
		if(brandIds[0] == '-'){
			brandIds.splice(0,1);
		}
		var brandIds =brandIds.toString();
		var supplier = $('#supplier').combobox('getValue');
		var moreThan = $('#moreThan').combobox('getValue');
		var lessThan = $('#lessThan').combobox('getValue');
		var helpCode = $('#helpCode').combobox('getValue');
		var thirdEncode = $('#thirdEncode').combobox('getValue');
		var artno = $('#artNo').val();
		var goodsName = $('#goodsName').combobox('getValue');
		var selfEncode = $('#selfEncode').val();
		var sumType = $("input[name='sumType']:checked").val();
		var tbRadio = $("input[name='tbRadio']:checked").val();
        var filters = {
        		area:area,
        		shop:shopIds,
        		goodsType:goodsType,
        		brand:brandIds,
        		supplier:supplier,
        		moreThan:moreThan,
        		lessThan:lessThan,
        		helpCode:helpCode,
        		thirdEncode:thirdEncode,
        		artno:artno,
        		goodsName:goodsName,
        		selfEncode:selfEncode,
        		sumType:sumType,
        		tbRadio:tbRadio,
				shopType: "'加盟','直营'",
        };
        var grid_data = {'filters': JSON.stringify(filters)};
		var cond = getCond();
		if(!Util.nvl(cond) && cond == false){
			return ;
		}
		var param = Param.getReadCmd();
		var dgCol;
		if(sumType==10 && tbRadio == 1){
			param[Param.CMDTYPEKEY] = 0;
			dgCol = [[
					{field: 'SHOP_ID',title: '分店编码',width: 60,align:'center'},
				    {field: 'BAR_CODE',title: '货号',width: 120,align:'center',sortable:true},
				    {field: 'PRODUCT_NAME',title: '品名',width: 200,align:'center',sortable:true},
				    {field: 'SELF_CODE',title: '自编码',width: 70,align:'center'},
				    {field: 'HELP_CODE',title: '助记码',width: 70,align:'center'},
				    {field: 'SHORT_NAME',title: '简称',width: 200,align:'center'},
				    {field: '_t',title: '第三方编码',width: 70,align:'center'},
				    {field: 'UNIT',title: '单位',width: 50,align:'center'},
				    {field: 'SPEC',title: '规格',width: 70,align:'center'},
				    {field: 'STOCKB',title: '库存数量(包)',width: 100,align:'center'},
				    {field: 'STOCKB',title: '装箱数',width: 100,align:'center'},
				    {field: 'CST_PRICE',title: '成本价',width: 100,align:'center'},
				    {field: 'RTL_PRICE_AMOUNT',title: '库存金额',width: 100,align:'center'},
				    {field: 'PRODUCT_TYPE_ID',title: '类别编码',width: 60,align:'center'},
				    {field: 'PROD_TYPE_NAME',title: '类别名称',width: 70,align:'center'},
				    {
				    	field: 'BRAND_ID',
				    	title: '品牌编码',
				    	width: 60,
				    	align:'center',
				    	formatter: function(val, row){
				    		if(val=="-1" || val=="" || val==null){
				    			return "";
				    		}
				    	}
				    },
				    {field: 'BRAND_NAME',title: '品牌名称',width: 60,align:'center'},
				    {field: 'AREA_ID',title: '区域编码',width: 60,align:'center'},
				    {field: 'AREA_NAME',title: '分店区域',width: 60,align:'center'},
				    {field: 'SUPPLIER_ID',title: '供应商编码',width: 70,align:'center'},
				    {field: 'SUPPLIER_NAME',title: '供应商名称',width: 70,align:'center'},
				    {field: 'SPEC',title: '进货规格',width: 70,align:'center'},
			]]
		}else if(sumType==10 && tbRadio == 0){
			param[Param.CMDTYPEKEY] = 0;
			dgCol = [[
					{field: 'SHOP_ID',title: '分店编码',width: 60,align:'center'},
				    {field: 'BAR_CODE',title: '货号',width: 120,align:'center',sortable:true},
				    {field: 'PRODUCT_NAME',title: '品名',width: 200,align:'center',sortable:true},
				    {field: 'SELF_CODE',title: '自编码',width: 70,align:'center'},
				    {field: 'HELP_CODE',title: '助记码',width: 70,align:'center'},
				    {field: 'SHORT_NAME',title: '简称',width: 200,align:'center'},
				    {field: '_t',title: '第三方编码',width: 70,align:'center'},
				    {field: 'UNIT',title: '单位',width: 50,align:'center'},
				    {field: 'SPEC',title: '规格',width: 70,align:'center'},
				    {field: 'STOCKT',title: '库存数量(条)',width: 100,align:'center'},
				    {field: 'STOCKT',title: '装箱数',width: 100,align:'center'},
				    {field: 'CST_PRICE',title: '成本价',width: 100,align:'center'},
				    {field: 'RTL_PRICE_AMOUNT',title: '库存金额',width: 100,align:'center'},
				    {field: 'PRODUCT_TYPE_ID',title: '类别编码',width: 60,align:'center'},
				    {field: 'PROD_TYPE_NAME',title: '类别名称',width: 70,align:'center'},
				    {
				    	field: 'BRAND_ID',
				    	title: '品牌编码',
				    	width: 60,
				    	align:'center',
				    	formatter: function(val, row){
				    		if(val=="-1" || val=="" || val==null){
				    			return "";
				    		}
				    	}
				    },
				    {field: 'BRAND_NAME',title: '品牌名称',width: 60,align:'center'},
				    {field: 'AREA_ID',title: '区域编码',width: 60,align:'center'},
				    {field: 'AREA_NAME',title: '分店区域',width: 60,align:'center'},
				    {field: 'SUPPLIER_ID',title: '供应商编码',width: 70,align:'center'},
				    {field: 'SUPPLIER_NAME',title: '供应商名称',width: 70,align:'center'},
				    {field: 'SPEC',title: '进货规格',width: 70,align:'center'},
			]]
		}else if(sumType==11){
			param[Param.CMDTYPEKEY] = 1;
			dgCol = [[
				{field: 'SHOP_ID',title: '分店编码',width: 60,align:'center'},
				{field: 'SHOP_NAME',title: '分店名称',width: 250,align:'center',sortable:true},
				{field: 'BAR_CODE',title: '货号',width: 120,align:'center',sortable:true},
				{field: 'PRODUCT_NAME',title: '品名',width: 200,align:'center',sortable:true},
				{field: 'SELF_CODE',title: '自编码',width: 70,align:'center'},
				{field: 'HELP_CODE',title: '助记码',width: 70,align:'center'},
				{field: 'SHORT_NAME',title: '简称',width: 200,align:'center'},
				{field: '_t',title: '第三方编码',width: 70,align:'center'},
				{field: 'UNIT',title: '单位',width: 50,align:'center'},
				{field: 'SPEC',title: '规格',width: 70,align:'center'},
				{field: 'STOCK',title: '库存数量',width: 100,align:'center'},
				{field: 'STOCK',title: '装箱数',width: 100,align:'center'},
				{field: 'CST_PRICE',title: '成本价',width: 100,align:'center'},
				{field: 'RTL_PRICE_AMOUNT',title: '库存金额',width: 100,align:'center'},
				{field: 'PRODUCT_TYPE_ID',title: '类别编码',width: 60,align:'center'},
				{field: 'PROD_TYPE_NAME',title: '类别名称',width: 70,align:'center'},
				{
					field: 'BRAND_ID',
					title: '品牌编码',
					width: 60,
					align:'center',
					formatter: function(val, row){
						if(val=="-1" || val=="" || val==null){
							return "";
						}
					}
				},
				{field: 'BRAND_NAME',title: '品牌名称',width: 60,align:'center'},
				{field: 'AREA_ID',title: '区域编码',width: 60,align:'center'},
				{field: 'AREA_NAME',title: '分店区域',width: 60,align:'center'},
				{field: 'SUPPLIER_ID',title: '供应商编码',width: 70,align:'center'},
				{field: 'SUPPLIER_NAME',title: '供应商名称',width: 70,align:'center'},
				{field: 'SPEC',title: '进货规格',width: 70,align:'center'}
				]]
		}else if(sumType==12){
			param[Param.CMDTYPEKEY] = 2;
			dgCol = [[
					    {field: '_rn',title: '行号',align: 'center',width: 30
					    	,formatter: function(value, row, index) {
					    		return index+1;
					    	}
						},
						 {field: 'PRODUCT_TYPE_ID',title: '类别编码',width: 60,align:'center'},
						{field: 'PROD_TYPE_NAME',title: '类别名称',width: 70,align:'center'},
					    {field: 'STOCK',title: '库存数量',width: 60,align:'center'},
					    //{field: '_s',title: '寄存库存',width: 60,align:'center'},
					    {field: 'STOCK',title: '装箱数',width: 50,align:'center'},
					    {field: 'RTL_PRICE_AMOUNT',title: '库存金额',width: 60,align:'center'},
					    //{field: '_f',title: '寄存库存金额',width: 80,align:'center'},
					    {field: '_c',title: '不含税库存金额',width: 90,align:'center'}	   	    	   
				]];
		}else if(sumType==13){
			param[Param.CMDTYPEKEY] = 3;
			dgCol = [[
					    {field: '_rn',title: '行号',align: 'center',width: 30
					    	,formatter: function(value, row, index) {
					    		return index+1;
					    	}
						},
						{field: 'BRAND_ID',title: '品牌编码',width: 60,align:'center'},
					    {field: 'BRAND_NAME',title: '品牌名称',width: 60,align:'center'},
					    {field: 'STOCK',title: '库存数量',width: 60,align:'center'},
					    //{field: '_s',title: '寄存库存',width: 60,align:'center'},
					    {field: 'STOCK',title: '装箱数',width: 50,align:'center'},
					    {field: 'RTL_PRICE_AMOUNT',title: '库存金额',width: 60,align:'center'},
					    //{field: '_f',title: '寄存库存金额',width: 80,align:'center'},
					    {field: '_c',title: '不含税库存金额',width: 90,align:'center'}	   	    	      
				]];
		}else if(sumType==14){
			param[Param.CMDTYPEKEY] = 4;
			dgCol = [[
					    {field: '_rn',title: '行号',align: 'center',width: 30
					    	,formatter: function(value, row, index) {
					    		return index+1;
					    	}
						},
						{field: 'SUPPLIER_ID',title: '供应商编码',width: 70,align:'center'},
					    {field: 'SUPPLIER_NAME',title: '供应商名称',width: 70,align:'center'},
					    {field: 'STOCK',title: '库存数量',width: 60,align:'center'},
					    //{field: '_s',title: '寄存库存',width: 60,align:'center'},
					    {field: 'STOCK',title: '装箱数',width: 50,align:'center'},
					    {field: 'RTL_PRICE_AMOUNT',title: '库存金额',width: 60,align:'center'},
					    //{field: '_f',title: '寄存库存金额',width: 80,align:'center'},
					    {field: '_c',title: '不含税库存金额',width: 90,align:'center'}	   	       	   
				]];
		}
		param = Param.buildParam(param, cond);
		$('#dg').datagrid({
			url: CONTEXT_PATH + '/ktcount/storeQueryList',
			//url: CONTEXT_PATH +url,
			queryParams: filters,
			method: 'POST',
			columns:dgCol,
			//remoteSort:false,
			rownumbers : false,
			pagination:false,
			//loadFilter:pagerFilter,
			//pageList:[100,200,300,400,500,10000],
			//pageSize:10000,
			//total:100,
			//pageNumber:1,
//			onLoadSuccess: function(data){
//				onLoadSuccess();
//			}
		});
	};
	// 导出excel
	var onExpExcel = function() {
		var cond = getCond();
		if (!cond) {
			return false;
		}
		var param = Param.getExportCmd();
		param = Param.buildParam(param, cond);
		if(sumType==10){
			param[Param.CMDTYPEKEY] = 0;
		}else if(sumType==11){
			param[Param.CMDTYPEKEY] = 1;
		}else if(sumType==12){
			param[Param.CMDTYPEKEY] = 2;
		}else if(sumType==13){
			param[Param.CMDTYPEKEY] = 3;
		}else if(sumType==14){
			param[Param.CMDTYPEKEY] = 4;
		}
		Util.doPost(url, param, function(data) {
			if (data && data.file) {
				win.open(data.file);
			} else if (data && data.stateMsg) {
				Util.msg.alert(data.stateMsg);
				return false;
			}
		});
	};
	
	//导出
   var daochu = function(){   
//	   var startTime = $('#startTime').datebox('getValue');	
//	   var endTime = $('#endTime').datebox('getValue');		
	   var area = $('#area').combobox('getText');
	   var shop = $('#shop').combobox('getText');
	   $('#dg').tableExport({type:'xls',fileName:'库存查询表',tableName:'库存查询表',AREA:area,SHOP:shop});
   }
	   
	//区域树状
	 var hbg = function(){
		 $('#win').dialog('open');
	        var setting = {
	                view: {
	                    dblClickExpand: false,
	                    showLine: true,
	                    selectedMulti: false
	                }, 
	                check: {
                       enable: true,
                       chkStyle: "checkbox",
                   },
	                data: {
	                    simpleData: {
	                        enable: true,
	                        idKey: "ZONE_CODE",
	                        pIdKey: "PARENT_ID",
	                        rootPId: '',
	                        areaCode:"ZONE_CODE"
	                    },
	    				key: {
	                        name: 'ZONE_NAME'
	    				}
	                },
	                callback: { //回调函数
	    				  onDblClick: function (treeId, treeNode) {
	    					  
	    					  var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	    					  var node = treeObj.getSelectedNodes();//点击节点后 获取节点数据
	                       // $("#area").val(node[0].text)
	                        $('#area').combobox('setValue', node[0].text);
	                        $("#typeId").val(node[0].tId)
	                        layer.close(modalIndex)
	    				  }
	                }
	            }
	        
			var param = Param.getReadCmd();
			var cond = {};
			param = Param.buildParam(param,cond);
			param[Param.CMDTYPEKEY] = 0;
			param[Param.CMDVALUEKEY] = 1;
			param = {
					zoneCode:'',
					state:1
			}
	        $.ajax({
				url: CONTEXT_PATH + '/ktcount/getArea',
				data : param,
	            type : "post",
	            dataType : "json",
	            async : false,
	            success : function(data) {
	                var dataArray = data;
	                $.fn.zTree.init($("#treeDemo"), setting, dataArray);
	                $("#authorizationInfoContentBrodBrand").removeClass("hide");
	            },
	            error : function () {
	                layer.closeAll('loading');
	                layer.msg("网络异常")
	            }
	        });
	 }
	 //区域确定
	 var bt = function(){
		 var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
		 var nodes = treeObj.getCheckedNodes();
	     var areaNameVal = "",areaCodeVal = "";
	     for(var i = 0,nodesLen = nodes.length;i < nodesLen;i++){
//	    	 if(!nodes[i]["isParent"]){
		    	 areaNameVal += nodes[i]["ZONE_NAME"]+",";
		    	 areaCodeVal += nodes[i]["ZONE_CODE"]+",";
//	    	 }
	     }
	     if(nodes.length > 0){
	    	 areaNameVal = areaNameVal.substring(0,areaNameVal.length-1);
	    	 areaCodeVal = areaCodeVal.substring(0,areaCodeVal.length-1);
	     }
	     if(nodes.length == 0){
	    	 $('#area').combobox('setValue', '-');
	     }else{
	    	 $('#area').combobox('setValue', areaNameVal);
	     }
	     
	     $('#areaCode').val(areaCodeVal);
	     $('#win').dialog('close');
	     var cond = getCond2();
	     var param = Param.getReadCmd();
			param[Param.CMDTYPEKEY] = 1;
			param[Param.CMDVALUEKEY] = 1;
			param = Param.buildParam(param,cond);
			var param = {
					shopType:"'加盟','直营'",
					zoneCode:$("#areaCode").val()
			}
			$('#shop').combobox({
				url: CONTEXT_PATH + '/ktcount/getShop',
				queryParams : param,
				method : 'post',
				valueField: 'SHOP_ID',
			    textField: 'SHOP_NAME',
			    loader: Util.combox.loader
			}).combobox('setValue', '-');
		  
	 }
	 
	//商品类型树
	 var prodType = function(){
		 $('#prodTypeWin').dialog('open');
	        var setting = {
	                view: {
	                    dblClickExpand: false,
	                    showLine: true,
	                    selectedMulti: false
	                }, 
	                check: {
                        enable: true,
                        chkStyle: "checkbox",
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "TYPE_ID",
                            pIdKey: "PARENT_ID",
                            rootPId: '',
                            typeId:"TYPE_ID"
                        },
        				key: {
                            name: 'TYPE_NAME'
        				}
                    },
	            }	        
	        	var filters = {
	                "rules": [
	                    {
	                        "field": "state",
	                        "data": '1'
	                    }
	                ]
	            };
	            var queryModels = {
	                page: '1',
	                rows: '10000',
	                filters: JSON.stringify(filters), 
	            };
	            var param = Param.getReadCmd();
				var cond1 = {};
				param = Param.buildParam(param,cond1);
				param[Param.CMDTYPEKEY] = 2;
				param[Param.CMDVALUEKEY] = 1;
	        $.ajax({
	        	url: CONTEXT_PATH + '/ktcount/getGoodsType',
				data : param,
	            type : "get",
	            dataType : "json",
	            async : false,
	            success : function(data) {
	                var dataArray = data;
	                $.fn.zTree.init($("#treeDemo2"), setting, dataArray);
	                $("#authorizationInfoContentBrodBrand").removeClass("hide");
	            },
	            error : function () {
	                layer.closeAll('loading');
	                layer.msg("网络异常")
	            }
	        });
	 }
	 //商品类型确定
	 var proTypeBt = function(){
		 var treeObj = $.fn.zTree.getZTreeObj("treeDemo2");
		 var nodes = treeObj.getCheckedNodes();
	     var typeNameVal = "",typeIdVal = "";
	     for(var i = 0,nodesLen = nodes.length;i < nodesLen;i++){
	    	 if(!nodes[i]["isParent"]){
	    		 typeNameVal += nodes[i]["TYPE_NAME"]+",";
		    	 typeIdVal += nodes[i]["TYPE_ID"]+",";
	    	 }
	     }
	     if(nodes.length > 0){
	    	 typeNameVal = typeNameVal.substring(0,typeNameVal.length-1);
	    	 typeIdVal = typeIdVal.substring(0,typeIdVal.length-1);
	     }
	     if(nodes.length = 0){
	    	 $('#goodsType').combobox('setValue', '-');
	     }else{
	    	 $('#goodsType').combobox('setValue', typeNameVal);
	     }
	     $('#typeId').val(typeIdVal);
	     $('#prodTypeWin').dialog('close');
	     var typeId = {
	    		 typeId:typeIdVal
	     }
		$('#brand').combobox({
			url: CONTEXT_PATH + '/ktcount/prodTypeLinkBrand',
			queryParams : typeId,
			method : 'post',
		    valueField: 'BRAND_CODE',
		    textField: 'BRAND_NAME',
		    loader: Util.combox.loader
		}).combobox('setValue', '-');
	 }
	
	// 初始化
	$(function(){
		// dg
		$('#dg').datagrid({
			fit: true,
			onLoadSuccess: compute,
			pagination:false,
			pageList:[100,200,300,400,500,10000],
			pageSize:100,
			columns: [[
			    {field: '_rn',title: '行号',align: 'center',width: 30
				    	,formatter: function(value, row, index) {
				    		return index+1;
				    	}
				},
				{field: 'SHOP_ID',title: '分店编码',width: 60,align:'center'},
			    {field: 'SHOP_NAME',title: '分店名称',width: 250,align:'center',sortable:true},
			    {field: 'BAR_CODE',title: '货号',width: 120,align:'center'},
			    {field: 'PRODUCT_NAME',title: '品名',width: 200,align:'center'},
			    {field: 'SELF_CODE',title: '自编码',width: 70,align:'center'},
			    {field: 'HELP_CODE',title: '助记码',width: 70,align:'center'},
			    {field: 'SHORT_NAME',title: '简称',width: 200,align:'center'},
			    {field: '_t',title: '第三方编码',width: 70,align:'center'},
			    {field: 'UNIT',title: '单位',width: 50,align:'center'},
			    {field: 'SPEC',title: '规格',width: 70,align:'center'},
			    {field: 'STOCK',title: '库存数量',width: 60,align:'center'}, 
			    //{field: '_s',title: '寄存库存',width: 60,align:'center'},
			    {field: 'STOCK',title: '装箱数',width: 50,align:'center'},
			    {field: 'CST_PRICE',title: '成本价',width: 50,align:'center'},
			    {field: 'RTL_PRICE_AMOUNT',title: '库存金额',width: 60,align:'center'},
			    //{field: '_f',title: '寄存库存金额',width: 80,align:'center'},
			    {field: 'PRODUCT_TYPE_ID',title: '类别编码',width: 60,align:'center'},
			    {field: 'PROD_TYPE_NAME',title: '类别名称',width: 70,align:'center'},
			    {field: 'BRAND_ID',title: '品牌编码',width: 60,align:'center'},
			    {field: 'BRAND_NAME',title: '品牌名称',width: 60,align:'center'},
			    {field: 'AREA_ID',title: '区域编码',width: 60,align:'center'},
			    {field: 'AREA_NAME',title: '分店区域',width: 60,align:'center'},
			    {field: 'SUPPLIER_ID',title: '供应商编码',width: 70,align:'center'},
			    {field: 'SUPPLIER_NAME',title: '供应商名称',width: 70,align:'center'},
			    {field: 'SPEC',title: '进货规格',width: 70,align:'center'},
			    {field: '_c',title: '不含税库存金额',width: 90,align:'center'}	   
			]]
		});
		//创建条件查询下拉组件
		createCondCombox();
		// 初始化时间
		var cdate = Util.date.format(new Date(), 'yyyy-MM-dd');
		$('#startTime').datebox('setValue', cdate);
		$('#endTime').datebox('setValue', cdate);
		
		$(":radio").click(function(){
			var radioValue = $(this).val();
			if(radioValue>9){
				sumType = radioValue;
			}else{
				pubFunction.setTime(radioValue);
			}
	    });
		
		// 执行查询
		$('#queryBtn').off('click').on('click', onQuery);
		// 执行导出
		//$('#exportBtn').on('click', onExpExcel);
		$('#exportBtn').on('click', daochu); 
		// 执行退出
		$('#closeBtn').on('click', pubFunction.CloseWebPage);
		// 执行打印
		$('#printBtn').on('click', pubFunction.PrintPage);
		// 区域弹窗
		$('#quyu').on('click', hbg);
		$('#sbt').on('click',bt);
		//商品类型弹窗 
		$('#prodType').on('click', prodType);
		$('#proTypeBt').on('click', proTypeBt);
		//店铺、品牌、供应商 获得焦点清除输入框
		$('#tdShop').on('change',shopChange);
		$('#tdBrand').on('change',brandChange);
		$('#tdSupplier').on('change',supplierChange);

	});
	
//    function onLoadSuccess() {
//        //添加“合计”列
//        $('#dg').datagrid('appendRow', {
//        	SHOP_ID: '<span class="subtotal">合计</span>',
//            STOCK: '<span class="subtotal">' + compute("STOCK") + '</span>',
//            CST_PRICE: '<span class="subtotal">' + compute("CST_PRICE") + '</span>',
//            RTL_PRICE_AMOUNT: '<span class="subtotal">' + compute("RTL_PRICE_AMOUNT") + '</span>',
//            _f: '<span class="subtotal">' + compute("_f") + '</span>',
//            _s: '<span class="subtotal">' + compute("_s") + '</span>',
//            _c: '<span class="subtotal">' + compute("_c") + '</span>',
//        });
//    }
    //指定列求和
//    function compute(colName) {
//        var rows = $('#dg').datagrid('getRows');
//        var total = 0;
//        for (var i = 0; i < rows.length; i++) {
//            total += parseFloat(rows[i][colName]);
//        }
//        return total;
//    }
    
    function compute() {
        var rows = $("#dg").datagrid("getRows")//获取当前的数据行
        //计算总和  STOCK  STOCK  CST_PRICE  RTL_PRICE_AMOUNT
        var stock = 0, cst_price = 0 
            , rtl_price_amount = 0, is_heji = 0;
        for (var i = 0; i < rows.length; i++) {
        	stock += parseFloat(rows[i]['STOCK']);
            cst_price += parseFloat(rows[i]['CST_PRICE']);
            rtl_price_amount += parseFloat(rows[i]['RTL_PRICE_AMOUNT']);
            if (rows[i]['areaname'] == "<b>合计：</b>") {
                is_heji = 1;
            }
         }
        if (is_heji == 0) {
        	//新增一行显示统计信息 PROD_TYPE_NAME
            if(sumType==10){
                $("#dg").datagrid('appendRow', {
                	SHOP_ID: '<b>合计：</b>',
                    STOCK: stock.toFixed(2),
    				CST_PRICE: cst_price.toFixed(2),
    				RTL_PRICE_AMOUNT:rtl_price_amount.toFixed(2),
                });
            }else if(sumType==11){
                $("#dg").datagrid('appendRow', {
                	SHOP_ID: '<b>合计：</b>',
                	STOCK: stock.toFixed(2),
     				CST_PRICE: cst_price.toFixed(2),
     				RTL_PRICE_AMOUNT:rtl_price_amount.toFixed(2),
                });
            }
        }
    }
    //处理分页
    function pagerFilter(data){
    	var data = data.rows;
    	 // 判断数据是否是数组
        if (typeof data.length == 'number' && typeof data.splice == 'function'){   
            data = {
                total: data.length,
                rows: data
            }
            console.log(data);
        }
        var dg = $('#dg');
        var opts = dg.datagrid('options');
        var pager = dg.datagrid('getPager');
        pager.pagination({
            onSelectPage:function(pageNum, pageSize){
                opts.pageNumber = pageNum;
                opts.pageSize = pageSize;
                pager.pagination('refresh',{
                    pageNumber:pageNum,
                    pageSize:pageSize
                });
                dg.datagrid('loadData',data);
            }
        });
        if (!data.originalRows){
            data.originalRows = (data.rows);
        }
        var start = (opts.pageNumber-1)*parseInt(opts.pageSize);
        var end = start + parseInt(opts.pageSize);
        data.rows = (data.originalRows.slice(start, end));
        return data;
    }
})(jQuery, window, document);
